package com.example.alarmcontrolpanel;

import java.util.Calendar;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.widget.Toast;

public class AlarmReceiver extends BroadcastReceiver
{
	int AlarmType = AlarmManager.RTC_WAKEUP;
	AlarmManager alarms;
	Intent alarmReceiver;
	
	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		int alarm_id=Integer.parseInt(intent.getStringExtra("ALARM_ID"));
		
		AlramRecord alarms = createAlarmFromId(alarm_id,context);
		
		
		String message = "Hellooo, alrm worked ----\n and Alarm Id is: "+alarms.alarm_id+alarms.desc;
		
		Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
		setNextAlarm(context, alarms);
		Intent intent2 = new Intent(context, Main.class);
		
        intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent2);
        
	}
	public AlramRecord createAlarmFromId(int id, Context con)
	{
		int alarm_id=0;
		String desc=null;
		int[] repeatDay = new int[7];
		int repeatType=0;
		Calendar Cal = Calendar.getInstance();
		
		SharedPreferences sharedAlarmList = con.getSharedPreferences("com.AlarmList", 0);
		String newStr=sharedAlarmList.getString("Key"+Integer.toString(id), null);
		
		String calcStr;
		if(newStr!=null) /** This checks to confirm that there is something in the string */
		{
			for(int i=0;i<5;i++) /** From here the code goes for Sting manipulation */
			{
				if(i<4)
				{
					calcStr = newStr.substring(0,newStr.indexOf('`'));
					newStr = newStr.substring(newStr.indexOf('`')+1);
				}
				else
				{
					calcStr = newStr;
				}
				switch(i)
				{
					case 0://Alarm Id
					{
						alarm_id  = Integer.parseInt(calcStr);
						break;
					}
					case 1://Description
					{
						desc  = calcStr;
						break;
					}
					case 2://Repeat Day
					{
						for(int m=0;m<7;m++)
						{
							repeatDay[m]=Integer.parseInt(Character.toString(calcStr.charAt(m)));
						}
						break;
					}
					case 3://repeat Type
					{
						repeatType = Integer.parseInt(calcStr);
						break;
					}
					case 4://Calendar
					{
						Cal= Calendar.getInstance();
						Cal.setTimeInMillis(Long.parseLong(calcStr));
						break;
					}
				}
			}
		}
		return(new AlramRecord(alarm_id, desc, repeatDay, repeatType, Cal));
	}
	

	/**
	 * In setNextAlarm, the Device will set the alarm as per the
	 * repeating has been set.
	 * 
	 * for repeatType=0,
	 * Find the current Day,
	 * check the next Day for Alarm.
	 * add the number of days to the alarm.
	 * 
	 * for repeatType=1, then delete the alarm and shift the next alarms occupying the
	 * deleted alarm id.
	 * 
	 * for repeatType=2, increase the alarm by one month
	 * 
	 * for repeatType=3, increase the alarm by one year
	 * 
	 * 
	 * Note: Don't change the complete string we just need to change the Calendar in case of repeatType=0,2,3.
	 * 
	 * **/
	
	public void setNextAlarm(Context con, AlramRecord alarm)
	{
		Calendar localCal = Calendar.getInstance();
		/**
		 * desc - description for the alarm
		 * repeatDay - Days to repeat
		 * createTime - Time of creation of Alarm
		 * createDate - Date of creation of Alarm
		 * repeatType - Type of repeat
			 * 0 - repeat Days
			 * 1 - repeat None
			 * 2 - repeat Monthly
			 * 3 - repeat Yearly
		 */
		
		switch(alarm.repeatType)
		{
			case 0://repeat Days
			{
				int i;
				int j=localCal.get(Calendar.DAY_OF_WEEK)-1;
				
				
				int check=0;
				/**
				 * This code checks if the user has selected any repeating day or not.
				 * if yes then it will be repeated on that day else
				 * will be triggered when the clock ticks the time next.
				 * 
				 */
				for(i=0;i<7;i++)
				{
					if(alarm.repeatDay[i]==1)
					{
						check=1;
						break;
					}
				}
				if(check==0)
				{
					if(alarm.Cal.getTimeInMillis()<localCal.getTimeInMillis())
					{
						alarm.Cal.add(Calendar.DATE, 1);
					}
				}
				else
				{
					check=0;
					int counter=0;
					i=j;
					//Ab hua tension
					for(int m=0;m<7;m++)					// This is to check for the next coming repeat Day
					{			
						if(i==6)
						{
							if(alarm.Cal.getTimeInMillis()<localCal.getTimeInMillis())
							{
								i=0;
							}
							else
							{
								if(alarm.repeatDay[i]==1)
									break;
								else
									i=0;
							}
						}									//
						if(alarm.repeatDay[i]==1)			//
							break;							//
						else
							i++;
						counter++;
					}
					alarm.Cal.add(Calendar.DATE, counter);
				}
				SharedPreferences sharedAlarmList = con.getSharedPreferences("com.AlarmList", 0);
				sharedAlarmList.edit().putString("Key"+Integer.toString(alarm.alarm_id), alarm.prepareAlarmStatement()).apply();
				alarmReceiver = new Intent(con, AlarmReceiver.class);
				alarmReceiver.putExtra("ALARM_ID", Integer.toString(alarm.alarm_id));
				alarms = (AlarmManager) con.getSystemService(Context.ALARM_SERVICE);
				PendingIntent PendingAlarm = PendingIntent.getBroadcast(con, alarm.alarm_id, alarmReceiver, PendingIntent.FLAG_CANCEL_CURRENT);
				alarms.set(AlarmManager.RTC_WAKEUP, alarm.Cal.getTimeInMillis(), PendingAlarm);
				break;
			}
			case 1:
			{
				/***
				 * Delete this shared Preference.
				 * Use Queue Concept
				 * */
				SharedPreferences sharedPrefCounter = con.getSharedPreferences("com.Counter", 0);
				int maxCount=sharedPrefCounter.getInt("Count", 0);
				
				int startCount = alarm.alarm_id;
				int endCount = maxCount-1;
				
				SharedPreferences getAlarm = con.getSharedPreferences("com.AlarmList", 0);
				
				for(;startCount<endCount;startCount++)
				{
					String postAlarmString = getAlarm.getString("Key"+Integer.toString(startCount+1), null);
					String postAlarmId = postAlarmString.substring(0,postAlarmString.indexOf('`'));
					
					int newAlarmId = Integer.parseInt(postAlarmId)-1;
					
					String postRestOfString = Integer.toString(newAlarmId)+postAlarmString.substring(postAlarmString.indexOf('`'));
					
					getAlarm.edit().putString("Key"+Integer.toString(startCount), postRestOfString).apply();
				}
				sharedPrefCounter.edit().putInt("Count", endCount).commit(); //decreased the count
				sharedPrefCounter.edit().apply();
				SharedPreferences toDelete = con.getSharedPreferences("com.AlarmList", 0);
				toDelete.edit().remove("Key"+Integer.toString(endCount)).apply();
				break;
			}
			case 2:
			{
				//repeat Monthly
				alarm.Cal.add(Calendar.MONTH, 1);
				SharedPreferences sharedAlarmList = con.getSharedPreferences("com.AlarmList", 0);
				sharedAlarmList.edit().putString("Key"+Integer.toString(alarm.alarm_id), alarm.prepareAlarmStatement()).apply();
				alarmReceiver = new Intent(con, AlarmReceiver.class);
				alarmReceiver.putExtra("ALARM_ID", Integer.toString(alarm.alarm_id));
				alarms = (AlarmManager) con.getSystemService(Context.ALARM_SERVICE);
				PendingIntent PendingAlarm = PendingIntent.getBroadcast(con, alarm.alarm_id, alarmReceiver, PendingIntent.FLAG_CANCEL_CURRENT);
				alarms.set(AlarmManager.RTC_WAKEUP, alarm.Cal.getTimeInMillis(), PendingAlarm);
				break;
			}
			case 3:
			{
				//repeat Yearly
				alarm.Cal.add(Calendar.YEAR,1);
				SharedPreferences sharedAlarmList = con.getSharedPreferences("com.AlarmList", 0);
				sharedAlarmList.edit().putString("Key"+Integer.toString(alarm.alarm_id), alarm.prepareAlarmStatement()).apply();
				alarmReceiver = new Intent(con, AlarmReceiver.class);
				alarmReceiver.putExtra("ALARM_ID", Integer.toString(alarm.alarm_id));
				alarms = (AlarmManager) con.getSystemService(Context.ALARM_SERVICE);
				PendingIntent PendingAlarm = PendingIntent.getBroadcast(con, alarm.alarm_id, alarmReceiver, PendingIntent.FLAG_CANCEL_CURRENT);
				alarms.set(AlarmManager.RTC_WAKEUP, alarm.Cal.getTimeInMillis(), PendingAlarm);
				break;
			}
		}
	}
}